package com.jf.nep.scene;

import java.io.InputStream;
import java.nio.ByteBuffer;

import de.matthiasmann.twl.utils.PNGDecoder;
import de.matthiasmann.twl.utils.PNGDecoder.Format;

public class TerrainBuilder {
    public static final int MAX_INTERPOLATED_SIZE = 10000000;
    
    public static Terrain loadTerrain(String resourceName, float scale) throws Exception {
        InputStream is = TerrainBuilder.class.getResourceAsStream(resourceName);
        PNGDecoder decoder = new PNGDecoder(is);
        
        int width = decoder.getWidth();
        int depth = decoder.getHeight();
        if (width*depth > MAX_INTERPOLATED_SIZE) {
            throw new Exception("Too big terrain!");
        }
        
        ByteBuffer buffer = ByteBuffer.allocateDirect(width * depth);
        decoder.decode(buffer, decoder.getWidth(), Format.LUMINANCE);
        buffer.flip();
        is.close();

        Terrain terrain = new Terrain(width,depth);
        byte[] row = new byte[width];
        for (int z = 0; z < depth; z++) {
            buffer.get(row, 0, width);
            float[] heights = terrain.getHeightsAtZ(z);
            for (int x = 0; x < width; x++) {
                heights[x] = (float)row[x]/scale;
            }
        }        
        
        return terrain;
    }
}
